package learn.spring.tx.service;

import learn.spring.base.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.UUID;

/**
 * @author 执笔
 * @date 2021/7/29  14:18
 */
@Service
public class UserService {
    @Autowired
    private UserDao userDao;


    @Transactional
    public void testSuccess(){
        userDao.add("123", System.currentTimeMillis());
        userDao.add("456", System.currentTimeMillis());
    }

    @Transactional
    public void testFail(){
        userDao.add(UUID.randomUUID().toString(), System.currentTimeMillis());
        int i = 1/0;
        userDao.add(UUID.randomUUID().toString(), System.currentTimeMillis());
    }

    @Transactional(rollbackFor = Exception.class)
    public void testException() throws Exception {
        try {
            userDao.add(UUID.randomUUID().toString(), System.currentTimeMillis());
            int i = 1/0;
            userDao.add(UUID.randomUUID().toString(), System.currentTimeMillis());
        }catch (Exception e){
            throw new Exception();
            // 手动回滚
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
    }
}
